import { formatTimeToStr } from './date'
import {isNumber} from "./validate";

export const formatBoolean = (bool) => {
  if (bool !== null) {
    return bool ? '是' : '否'
  } else {
    return ''
  }
}
export const formatDate = (time) => {
  if (time !== null && time !== '') {
    var date = new Date(time)
    return formatTimeToStr(date, 'yyyy-MM-dd hh:mm:ss')
  } else {
    return ''
  }
}

export const formatSize = (row, col) => {
  return (row[col.property]/ (1024 * 1024)).toFixed(3) + "m";
}

export const formatTime = (row, col) => {
  let time = row[col.property];
  if (isNumber(time) && String(time).length === 10) time = time * 1000;
  let d = new Date(time);
  if (d.getFullYear() === 1) return "";
  return formatDate(d);
}

export const filterDict = (value, options) => {
  const rowLabel = options && options.filter(item => item.value === value)
  return rowLabel && rowLabel[0] && rowLabel[0].label
}

export const filterDataSource = (dataSource, value) => {
  if (Array.isArray(value)) {
    return value.map(item => {
      const rowLabel = dataSource && dataSource.find(i => i.value === item)
      return rowLabel?.label
    })
  }
  const rowLabel = dataSource && dataSource.find(item => item.value === value)
  return rowLabel?.label
}

const colorToHex = u=>{
  let e = u.replace("#", "").match(/../g);
  for (let t = 0; t < 3; t++)
    e[t] = parseInt(e[t], 16);
  return e
}

const  hexToColor = (u,e,t)=>{
  let a = [u.toString(16), e.toString(16), t.toString(16)];
  for (let n = 0; n < 3; n++)
    a[n].length === 1 && (a[n] = `0${a[n]}`);
  return `#${a.join("")}`
}
const  generateAllColors = (u,e)=> {
  let t = colorToHex(u);
  const target = [10, 10, 30];
  for (let a = 0; a < 3; a++)
  t[a] = Math.floor(t[a] * (1 - e) + target[a] * e);
  return hexToColor(t[0], t[1], t[2])
}

const generateAllLightColors = (u, e) => {
  let t = colorToHex(u);
  const target = [240, 248, 255]; // RGB for blue white color
  for (let a = 0; a < 3; a++)
    t[a] = Math.floor(t[a] * (1 - e) + target[a] * e);
  return hexToColor(t[0], t[1], t[2]);
}


function addOpacityToColor(u, opacity) {
  let t = colorToHex(u);
  return `rgba(${t[0]}, ${t[1]}, ${ t[2]}, ${opacity})`;
}

export function datetimeToSecond(datetime){
  let date = new Date(datetime);
  let t = date.getTime() / 1000;
  return Math.ceil(t);
}

export function json_decode(str){
  if (!str || str.length === 0) return null;
  try {
    const r = JSON.parse(str);
    return r;
  }catch (e) {
    console.error("json_decode_err:", e)
  }
  return null;
}

export function formatJSON(str){
  let ret = json_decode(str);
  if (!ret) return str;
  return JSON.stringify(ret, null, 6);
}